<?php

namespace app\admin\controller\insurance;

use app\admin\model\InsuranceReprule;
use app\admin\model\InsuranceCompany;
use app\admin\service\TriggerService;
use app\common\constants\MenuConstant;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\common\controller\AdminController;
use app\Request;
use think\App;
use think\response\Json;

#[ControllerAnnotation(title: '政策规则')]
class Reprule extends AdminController
{
    protected array $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = InsuranceReprule::class;
        $this->assign('p_titles', self::$model::$p_titles);
        $this->assign('company_list', InsuranceCompany::where('status', 1)->column('name', 'id'));

    }

    public $p_keys0 = [
        'company' => ['title' => '保险公司', 'id' => 0],
        'policy_num_sy' => ['title' => '商业险单号', 'id' => 1],
        'policy_num_jq' => ['title' => '交强险单号', 'id' => 2],
        'policy_num_jc' => ['title' => '驾乘险单号', 'id' => 3],
        'is_chesun' => ['title' => '车损', 'id' => 4],
        'insurer' => ['title' => '被保险人', 'id' => 5],
        'idcard' => ['title' => '身份证号', 'id' => 6],
        'carno' => ['title' => '车牌号', 'id' => 7],
        'cost_sy' => ['title' => '商业险金额', 'id' => 8],
        'cost_jq' => ['title' => '交强险金额', 'id' => 9],
        'cost_jc' => ['title' => '驾乘险金额', 'id' => 10],
        'cost_cc' => ['title' => '车船险金额', 'id' => 11],
        'start_at_sy' => ['title' => '商业险生效时间', 'id' => 12],
        'end_at_sy' => ['title' => '商业险失效时间', 'id' => 13],
        'start_at_jq' => ['title' => '交强险生效时间', 'id' => 14],
        'end_at_jq' => ['title' => '交强险失效时间', 'id' => 15],
        'mobile' => ['title' => '手机号', 'id' => 16],
        'agent' => ['title' => '代理人', 'id' => 17],
        'agent_factory' => ['title' => '代理厂', 'id' => 18],
        'third_party' => ['title' => '第三者保额', 'id' => 19],
        'car_type' => ['title' => '车辆类型', 'id' => 20],
        'is_transfer_owner' => ['title' => '过户', 'id' => 21],
        'is_driver_p' => ['title' => '司机险', 'id' => 22],
        'is_passenger_p' => ['title' => '乘客险', 'id' => 23],
    ];

    

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = self::$model::where($where)->count() ?: 0;
            $list  = self::$model::where($where)->order($this->sort)->page($page, $limit)->select()->toArray() ?: [];
            
            foreach ($list as $k => $v) {
                $list[$k]['p_key'] = self::$model::$p_titles[$v['p_key']];
            }
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    #[NodeAnnotation(title: '添加', auth: true)]
    public function add(Request $request): string
    {
        if ($request->isPost()) {
            $post = $request->post();
            $data = $post;
            $content_rep_rule = [];
            if (!empty($post['sou'])) {
                foreach($post['sou'] as $k => $v) {
                    $content_rep_rule[] = ['sou' => $v, 'rep' => $post['rep'][$k]];
                }
            }
            $data['content_rep_rule'] = $content_rep_rule;
            // $this->error('暂不支持添加', $content_rep_rule);
            try {
                $save = self::$model::create($data);
            }catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                // TriggerService::updateMenu();
                $this->success('保存成功');
            }else {
                $this->error('保存失败');
            }
        }

        return $this->fetch();
    }
    #[NodeAnnotation(title: '编辑', auth: true)]
    public function edit(Request $request, $id = 0): string
    {
        $row = self::$model::find($id);
        empty($row) && $this->error('数据不存在');
        if ($request->isPost()) {
            $post = $request->post();
            $data = $post;
            $content_rep_rule = [];
            if (!empty($post['sou'])) {
                foreach($post['sou'] as $k => $v) {
                    $content_rep_rule[] = ['sou' => $v, 'rep' => $post['rep'][$k]];
                }
            }
            $data['content_rep_rule'] = $content_rep_rule;
            try {
                $save = $row->save($data);
            }catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                // TriggerService::updateMenu();
                $this->success('保存成功');
            }else {
                $this->error('保存失败');
            }
        }
        $this->assign([
            'id'          => $id,
            'row'         => $row,
        ]);
        return $this->fetch();
    }
    #[NodeAnnotation(title: '删除', auth: true)]
    public function delete(Request $request): void
    {
        $this->checkPostRequest();
        $id  = $request->param('id');
        $row = self::$model::whereIn('id', $id)->select();
        empty($row) && $this->error('数据不存在');
        try {
            $save = $row->update(['status' => 0, 'delete_time' => time()]);
        }catch (\Exception $e) {
            $this->error('删除失败');
        }
        if ($save) {
            // TriggerService::updateMenu();
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }
    }

    #[NodeAnnotation(title: '属性修改', auth: true)]
    public function modify(Request $request): void
    {
        $this->checkPostRequest();
        $post = $request->post();
        $rule = [
            'id|ID'      => 'require',
            'field|字段' => 'require',
            'value|值'   => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        // if ($post['id'] == AdminConstant::SUPER_ADMIN_ID && $post['field'] == 'status') {
        //     $this->error('超级管理员状态不允许修改');
        // }
        $row = self::$model::find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        }catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    #[NodeAnnotation(title: '', auth: true)]
    public function getPkeys(): Json{
        return json(['code' => 0, 'msg' => 'ok', 'data' => $this->p_titles]);
    }
}
